package com.example.ketangpai_backend.service.impl;

import com.example.ketangpai_backend.Mapper.UserMapper;
import com.example.ketangpai_backend.entity.User;
import com.example.ketangpai_backend.entity.param.UserParam;
import com.example.ketangpai_backend.service.UserService;
import com.example.ketangpai_backend.utils.Encrypt;
import com.example.ketangpai_backend.utils.JwtUtil;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private UserMapper userMapper;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User login(UserParam userParam) throws Exception {
        // 对用户输入的密码进行加密
        String encodedPassword = Encrypt.AESEncrypt(userParam.getPassword());
        User user=userMapper.getByAccountAndPwd(userParam.getUsername(),encodedPassword);
        System.out.println(userParam);
        System.out.println(user==null);
        if(user!=null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("user", user);
            String jwt = JwtUtil.createToken(claims);
            user.setToken(jwt);
            claims.put("jwt", jwt);
            System.out.println(user.getToken());
            return user;
        }
        return null;
    }

    @Override
    public boolean create(User userCreateParam) throws Exception {
        // 对用户输入的密码进行加密
        String encodedPassword = Encrypt.AESEncrypt(userCreateParam.getPassword());
        userCreateParam.setPassword(encodedPassword);
        User user=userMapper.getByAccount(userCreateParam.getAccount());
        if(user!=null){
            return false;
        }else {
            userMapper.insert(userCreateParam);
            return true;
        }
    }
}
